﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using ExcelAutomator.Configuration;
using log4net;

namespace ExcelAutomator
{
	public static class ExecutorResolver
	{
		public static bool TryResolve(IEnumerable<Lazy<IExecutor, IExecutorMetadata>> candidates, ExecutorConfigurationWrapper cfg, out IExecutor executor)
		{
			var xDoc = XDocument.Parse(cfg.XmlConfiguration);
			foreach (var xElement in xDoc.Elements())
			{
				if (xElement.Name.Namespace.NamespaceName.Equals(Constants.ExecutorExtensionsNamespace))
				{
					if (xElement.Name.LocalName.Equals(cfg.Type))
					{
						var actionAttr = xElement.Attribute(XName.Get("action"));
						if (actionAttr != null)
						{
							var actionId = actionAttr.Value;

							var candidatesByActionId = candidates.ToDictionary(x => x.Metadata.ActionId);

							if (candidatesByActionId.ContainsKey(actionId))
							{
								executor = candidatesByActionId[actionId].Value;
								return true;
							}

							Log.Error(
								string.Format("The actionId '{0}' is not suported by the given executors. Please check your configuration.", actionId));

						}
						Log.Error(
							string.Format("The action attribute could not be resolved for the configuration: '{0}'.", cfg.XmlConfiguration));
					}
				}
			}
			executor = null;
			return false;
		}

		private static ILog Log
		{
			get { return LogManager.GetLogger(typeof (ExecutorResolver)); }
		}
	}
}
